package org.orqlog.server;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.Date;

public class ZkRegister {
    private CuratorFramework client;

    public ZkRegister() {

        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(3000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 5))
                .build();

        client.start();
        this.client = client;
        System.out.println("Zookeeper session established.");
    }


    /**
     * 在zk登记服务器节点
     * @param address
     * @throws Exception
     */
    public void registerServer(String address) throws Exception {
        String path = "/lg-server/" + address;
        client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, "init".getBytes());

        path = "/lg-server-restime/" + address;
        Stat stat =client.checkExists().forPath(path);
        if (stat == null) {
            client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, ((new Date()).getTime() + ",0").getBytes());
        }

        Thread.sleep(1000);
        System.out.println("Success create znode"+path);
    }

    /**
     * 记录服务响应时间
     * @param address
     * @param processTime
     * @throws Exception
     */
    public void registerProcessTime(String address, String processTime) throws Exception {
        String path = "/lg-server-restime/" + address;
        client.setData().forPath(path, processTime.getBytes());
    }
}
